class PlayView extends zysx.BaseView{

	private context: zysx.LayerMgr = zysx.LayerMgr.ins;

	private shareTime: number;

	private btn_back:eui.Image

	private btn_qz:eui.Group;

	//提示按钮
	private btn_ts: eui.Group;

	private list_play:eui.List;
	private btn_fx:eui.Group;

	private txt_point: eui.Label;

	private box_list: eui.Group;

	private currentCell: PlayCell;

	private giftGroup:eui.Group;
	private gift:eui.Image;
	//定义对象
	//对象池
	private playCells: Array<PlayCell>;

	private tsDatas: Array<ResultData>;

	private levelData: LevelData;

	private maxX: number = 0;

	private maxY: number = 0;

	//每个cell的宽高
	private itemPx: number;
	//金币
	private gold:eui.Label;
	//title
	private title:eui.Label;
	//游戏开始时间
	private startTime:number=0;
	
	private bg:eui.Image;

	//当前提示个数
	private tsFlg: number;

	private tips1:eui.Image;
	private tips:eui.Image;
	private teach_img:eui.Image;

	private shareFlg: string;

	private lxFlg: number;

	private lxCurrent: PlayCell;

	private isValite: boolean;

	private isShare:false;

	public constructor(data?) {
		super(data);
		this.skinName = "PlaySkin";
		this.levelData = new LevelData();
		this.shareFlg = '';
		this.isValite = true;
	}

	public initComponent(): void {
		super.initComponent();
	}

	public initListener(): void {
	
		super.initListener();
		
		this.addEvent(this.btn_back, egret.TouchEvent.TOUCH_TAP, this.openView, this);	
		this.addEvent(this.btn_qz, egret.TouchEvent.TOUCH_TAP, this.openView, this);
		this.addEvent(this.list_play, egret.TouchEvent.TOUCH_BEGIN, this.touchStart, this);
		this.addEvent(this.list_play, egret.TouchEvent.TOUCH_MOVE, this.moveItem, this);
		this.addEvent(this.btn_fx, egret.TouchEvent.TOUCH_TAP, this.share, this);
		this.addEvent(this.btn_ts, egret.TouchEvent.TOUCH_TAP, this.tiShi, this);
		this.addEvent(this.tips, egret.TouchEvent.TOUCH_TAP, this.openView, this);
		this.addEvent(this.tips1, egret.TouchEvent.TOUCH_TAP, this.openView, this);
		
		zysx.NotifyMgr.registerNotify(NotifyConst.UPDATE_GOLD,this.updateGold,this);
	}

	private share(){
		var that = this;
		ShareMgr.share({shareBack(){
			that.shareTime = that.shareTime || 0;
			if(that.shareTime < 1){
				that.shareTime ++;
				that.tiShi(true);
			}else{
				zysx.LayerMgr.ins.showTip("每关只能分享获得一次提示");
			}
		}})
		
	}
	public onOpen(data?): void {
		super.onOpen(data);

		//用户交互
		if(this.data && this.data.target){
			this.shareFlg = this.data.target;
			switch(this.shareFlg){
				case Consts.HELP: {
					//帮助他人
					this.levelData.chooseLevel(this.data.zhang, this.data.level);
					break;
				}
				case Consts.TONG_GUAN: {
					//提示
					this.isValite = false;
					this.levelData.chooseLevel(this.data.zhang, this.data.level);
					var tsTimer:egret.Timer = new egret.Timer(500, this.levelData.results.length);
					tsTimer.addEventListener(egret.TimerEvent.TIMER, this.luXiang, this);
					tsTimer.addEventListener(egret.TimerEvent.TIMER_COMPLETE, this.lxOver, this);
					tsTimer.start();
					break;
				}
			}
		}
		// var timer:egret.Timer = new egret.Timer(800, 3);
		// timer.addEventListener(egret.TimerEvent.TIMER, this.luXiang, this);
		// timer.start();
		this.initView();
	}

	private lxOver(){
		this.isValite = true;
		this.context.openView(ViewConst.TIPPANEL, {flg: 5,zhang: this.levelData.zhangjie, level: this.levelData.level}, LayerType.POP);
		return;
	}

	private luXiang(){
		if(this.lxFlg >= this.levelData.results.length){
			return;
		}
		this.isValite = false;
		this.lxFlg = this.lxFlg || 0;
		var item = this.tsDatas[this.lxFlg];
		var cell = <PlayCell>this.list_play.getChildAt(item.index);

		if(this.lxFlg == 0){
			this.lxFlg += 1;
			this.lxCurrent = cell;
			item = this.tsDatas[this.lxFlg];
			cell = <PlayCell>this.list_play.getChildAt(item.index);
		}

		var xFlg = cell.data.x - this.lxCurrent.data.x;
		var yFlg = cell.data.y - this.lxCurrent.data.y;
		var target: number;
		var outTarget: number;

		if(yFlg == 1){
			target = 0;
			outTarget = 2;
		}else if(yFlg == -1){
			target = 2;
			outTarget = 0
		}else if(xFlg == 1){
			target = 3
			outTarget = 1;
		}else if(xFlg == -1){
			target = 1;
			outTarget = 3;
		}
		cell.target = target;
		this.lxCurrent.outTarget = outTarget;
		
		cell.updatePage();
		this.lxCurrent.updatePage();
		this.lxCurrent = cell;
		this.lxFlg += 1;
	}

	private initView(): void{
		this.updateGold();
		this.checkGift();
		this.checkTips();
		
		this.playCells = [];
		this.tsDatas = [];
		this.title.text = this.levelData.chengjiu+" "+UserMgr.ins.chapter+" - "+UserMgr.ins.level
		
		var questions = this.levelData.questions;
		for(var i = 0; i < questions.length; i ++){
			var item = questions[i];
			var cell = new PlayCell(item);
			cell.index = i;
			this.list_play.addChild(cell);
			this.playCells.push(cell);
			
			this.maxX = item.x > this.maxX ? item.x : this.maxX;
			this.maxY = item.y > this.maxY ? item.y : this.maxY;

			//计算起点
			if(item.f == 1){
				this.currentCell = <PlayCell>this.list_play.getChildAt(cell.index);
			}
		}
		//提示
		this.tsDatas = this.levelData.results;
		
		var curResult;
		for(var i = 0; i < this.tsDatas.length; i ++){
			var obj = this.tsDatas[i];
			for(var y = 0; y < questions.length; y ++){
				var question = questions[y];
				if(obj.x == question.x && obj.y == question.y){
					this.tsDatas[i].index = y;
				}
			}
		}
		//计算list的宽高
		this.list_play.width = (this.maxX + 1) * CommonData.itemPx;
		this.list_play.height = (this.maxY + 1) * CommonData.itemPx;
		this.bg.width = this.list_play.width+25;
		this.bg.height = this.list_play.height+25;
		this.bg.x = this.list_play.x-5;
		this.bg.y = this.list_play.y-5;
	
		this.guide();
	}

	
	//******************************* method */

	private tiShi(decFlg?:boolean){
		if(!this.isValite || this.shareFlg){
			return;
		}
		var length = this.tsDatas.length;

		//所有已经提示完成
		if(this.tsFlg == length){
			return;
		}

		if(!decFlg){
			if(!UserMgr.ins.canDecGold(50)){
				//TODO 调用通用的tips
				zysx.LayerMgr.ins.showTip("金币不足");
				return;
			}else{
				UserMgr.ins.decGold(50);
			}
		}

		this.tsFlg = this.tsFlg || 0;
		this.tsFlg += 5;
		if(this.tsFlg > length){
			this.tsFlg = length;
		}
		var currentTs: PlayCell;
		for(var i = 0; i < this.tsFlg; i++){
			var index = this.tsDatas[i].index;
			var cell = <PlayCell>this.list_play.getChildAt(index);
			if(i == 0){
				currentTs = cell;
				continue;
			}else{
				var xFlg = cell.data.x - currentTs.data.x;
				var yFlg = cell.data.y - currentTs.data.y;
				var tsIn: number;
				var tsOut: number;

				if(yFlg == 1){
					tsIn = 0;
					tsOut = 2;
				}else if(yFlg == -1){
					tsIn = 2;
					tsOut = 0
				}else if(xFlg == 1){
					tsIn = 3
					tsOut = 1;
				}else if(xFlg == -1){
					tsIn = 1;
					tsOut = 3;
				}
				cell.tsIn = tsIn;
				currentTs.tsOut = tsOut;
				
				cell.updatePage();
				currentTs.updatePage();
				currentTs = cell;
			}
		}
	}
	
	//检查礼包
	private checkGift():void{
		if(!UserMgr.ins.gift1&& this.levelData.level > 2){
			this.giftGroup.visible = true;
			this.addEvent(this.giftGroup, egret.TouchEvent.TOUCH_TAP, this.openView, this);
			var tw = egret.Tween.get( this.gift, { loop:true} );
			tw.to({rotation:-20},120)
				.to({rotation:20},240)
				.to({rotation:-20},360)
				.to({rotation:0},480).wait(3600);
		}
	}


	private showTip1(){
		this.tips1.visible = true;;
		this.tips.visible = false;
	}
	
	private showTip(){
		this.tips1.visible = false;;
		this.tips.visible = true;
	}

	//检查提示
	private checkTips():void{
		if(this.levelData.zhangjie >= 4){
			return ;
		}

		if(this.levelData.zhangjie == 0 && this.levelData.level < 20){
			let that = this;
			var timer:egret.Timer = new egret.Timer(3000,1);
			timer.addEventListener(egret.TimerEvent.TIMER,this.showTip1,this);
			timer.start();
			return;
		}

		if(this.levelData.zhangjie > 0 || this.levelData.level >= 20   ){
			let that = this;
			var timer1:egret.Timer = new egret.Timer(10000,1);
			timer1.addEventListener(egret.TimerEvent.TIMER,this.showTip,this);
			
			var timer2:egret.Timer = new egret.Timer(30000,1);
			timer2.addEventListener(egret.TimerEvent.TIMER,this.showTip1,this);
			timer1.start();
			timer2.start();
			return;
		}
	}
	//新手引导
	private guide():void{
		if(!this.isValite){
			return;
		}
		if(this.levelData.zhangjie ==0 && this.levelData.level <=2){
			this.teach_img.visible = true;
			this.teach_img.touchEnabled = false;
			this.teach_img.includeInLayout = false;
			var tw = egret.Tween.get( this.teach_img, { loop:true} );
			this.teach_img.x = (zysx.StageMgr.stage.stageWidth - this.box_list.width)/2 + 30;
			this.teach_img.y = (this.box_list.height-this.list_play.height)/2+20;
			if(this.levelData.level == 0){
				tw.to({x:this.teach_img.x+CommonData.itemPx*2},1500);
				return;
			}
			if(this.levelData.level == 1){
				tw.to({x:this.teach_img.x+CommonData.itemPx*1},500)
				.to({y:this.teach_img.y + CommonData.itemPx },500)
				.to({x:this.teach_img.x+CommonData.itemPx*2},500);
				return;
			}
			if(this.levelData.level == 2){
				tw.to({x:this.teach_img.x+CommonData.itemPx*1},500)
				.to({y:this.teach_img.y + CommonData.itemPx },500)
				.to({x:this.teach_img.x},500)
				.to({y:this.teach_img.y + CommonData.itemPx*2 },500)
				.to({x:this.teach_img.x + CommonData.itemPx*2},1000);
			}
		}

	}

	private updateGold(): void {
		this.gold.text = ""+UserMgr.ins.gold;
	}

	//游戏开始
	private  touchStart(evt: egret.TouchEvent):void{
		if(this.startTime == 0){
			this.startTime = new Date().getTime();
		}
	}

	private moveItem(evt: egret.TouchEvent): void{
		if(!this.isValite){
			return;
		}
		// this.getCurrent(e)
		var cell = this.getCurrent(evt.stageX, evt.stageY);
		if (!cell || (cell.data.x == this.currentCell.data.x && cell.y == this.currentCell.data.y)) {
			return;
    	}
		var item = <PlayCell>this.list_play.getChildAt(cell.index);
		if(item.data.f == 2 || (item.data.x == this.currentCell.data.x && item.data.y == this.currentCell.data.y)){
			return;
		}
		if(item.data.f == 1 || item.data.a > 0){
			this.checkAll(item);
			return;
		}
		if((item.data.x == this.currentCell.data.x && Math.abs(item.data.y - this.currentCell.data.y) == 1) || 
		(item.data.y == this.currentCell.data.y && Math.abs(item.data.x - this.currentCell.data.x) == 1)){
			
			var target = 0;
			var outTarget = 0;
			var yFlg = item.data.y - this.currentCell.data.y;
			var xFlg = item.data.x - this.currentCell.data.x;

			if(yFlg == 1){
				target = 0;
				outTarget = 2;
			}else if(yFlg == -1){
				target = 2;
				outTarget = 0
			}else if(xFlg == 1){
				target = 3
				outTarget = 1;
			}else if(xFlg == -1){
				target = 1;
				outTarget = 3;
			}
			
			item.target = target;
			item.updatePage();
			item.data.a = this.currentCell.data.a + 1;
			this.currentCell.outTarget = outTarget;
			this.currentCell.updatePage();
			this.currentCell = item;

			this.checkFinish();
		}
	}

	private checkFinish(){
		for(var i = 0; i < this.playCells.length; i ++){
			var item = <PlayCell>this.list_play.getChildAt(i);
			if(item.data.a == 0 && item.data.f == 0){
				return false;
			}
		}
		//成功
		if(this.shareFlg == Consts.HELP){
			this.context.openView(ViewConst.TIPPANEL, {flg:2, zhang: this.levelData.zhangjie, level: this.levelData.level}, LayerType.POP);
			return;
		}

		var curLv = this.levelData.zhangjie * CommonData.zhangJie[this.levelData.zhangjie].num + this.levelData.level+1 ;
		let totalTime = (new Date().getTime() - this.startTime )/1000;
		if(this.levelData.level+1 >= CommonData.zhangJie[this.levelData.zhangjie].num){
			this.levelData.zhangjie = this.levelData.zhangjie+ 1;
			this.levelData.level = 1;
		}else{
			this.levelData.level = this.levelData.level + 1;
		}
		
		UserMgr.ins.setlevel(this.levelData.zhangjie+1,this.levelData.level+1);
		
		//结束时间

		let timeResult = CommonData.timeResult;
    	let itemTime = Math.round(10000 / (timeResult.length + 1));
    	let timeFlg = 0;
   	 	for (var i = 0; i < timeResult.length; i++) {
      	if (totalTime > timeResult[i]) {
        timeFlg += 1;
      		}
   		 }
    	var timeFight = Math.floor(Math.random() * itemTime + itemTime * (timeResult.length - timeFlg)) / 100;

		let ftotalTime = totalTime.toFixed(2);

		zysx.LayerMgr.ins.openView(ViewConst.SUCCESSVIEW, {time:ftotalTime,level:this.levelData.level,chapter:this.levelData.zhangjie+1,rank:timeFight}, LayerType.POP);
		if(curLv == 3){
			zysx.LayerMgr.ins.openView(ViewConst.FULIVIEW,3,LayerType.POP);	
		}
		
		//上报排行
		ShareMgr.sendRankData(this.levelData.level);

		return true;
	}

	private checkAll(cell: PlayCell){
		if(this.currentCell.data.x == cell.data.x && this.currentCell.data.y == cell.data.y){
			return;
		}
		if(cell.data.a > 0 || cell.data.f == 1){
			for(var i = 0; i < this.playCells.length; i ++){
				var item = <PlayCell>this.list_play.getChildAt(i);
				if(item.data.a > cell.data.a){
					item.target = -1;
					item.outTarget = -1;
					item.data.a = 0;
					item.updatePage();
				}
			}
			cell.outTarget = -1;
			cell.updatePage();
			this.currentCell = cell;
		}
	}

	private getCurrent(x: number, y: number): PlayCell{
		for(var i = 0; i < this.playCells.length; i ++){
			var item = this.playCells[i];
			if(item.hitTestPoint(x, y)){
				return item;
			}
		}
		return null;
	}

    private openView(evt: egret.TouchEvent): void {
		if(!this.isValite){
			return;
		}
		let viewName: string = "";
		let layType: number = LayerType.POP;
		let data = null;
		switch (evt.currentTarget) {
			case this.btn_back:
				layType = LayerType.UI;
				viewName = ViewConst.INDEXVIEW;
				data = 1;
				break;
			case this.btn_qz:
				viewName = ViewConst.TIPPANEL;
				data = {flg: 1, zhang: this.levelData.zhangjie, level: this.levelData.level};
				// data = 1;
				break;
			case this.btn_fx:
				ShareMgr.share();
				break;
			case this.giftGroup:
				viewName = ViewConst.FULIVIEW;
				data = 2;
				break;	
			case this.tips:
				this.tips.visible = false;
				break;
			case this.tips1:
				this.tips1.visible = false;
				break;		
		}
		if (viewName !="") {
			zysx.LayerMgr.ins.openView(viewName, data, layType);
		}
	}

	public onClose(): void {
		super.onClose();
	}
}
window["PlayView"] = PlayView;